<?php

class BookmarkTable extends Doctrine_Table
{
    /**
     * @return BookmarkTable 
     */
    public static function getInstance()
    {
      return Doctrine::getTable('Bookmark');
    }

    /**
     * Creates a generic Doctrine_Query to select bookmarks with their tags.
     *
     * @param int $limit the maximum number of bookmarks to retrieve
     * @return Doctrine_Query the generated query
     */
    private function createGenericQuery($limit = 10)
    {
      return $this->createQuery()
          ->select('b.*, t.*')
          ->from('Bookmark b')
          ->leftJoin('b.Tag t')
          ->limit($limit);
    }

    /**
     * Finds the first $limit bookmarks with their tags.
     *
     * @param int $limit the maximal number of bookmarks to retrieve
     * @return array the found bookmarks
     */
    public function findAllFetchTagsOrderByClicks($limit = 10)
    {
      $query = $this->createGenericQuery($limit);
      $query->orderBy('b.clicks DESC');
      return $query->fetchArray();
    }

    /**
     * Finds all the bookmarks that have the given associated Tag.
     *
     * @param string $tagName the discriminent tag
     * @return array an array containing the found bookmarks
     */
    public function findByTagFetchTags($tagName)
    {
      $q = $this->createGenericQuery();
      $q->addWhere('b.id IN (SELECT t2.bookmark_id FROM Tag t2 WHERE t2.name = ?)', $tagName);

      return $q->fetchArray();
    }

    /**
     * Creates tags based on their names specified in $tagList, then associate
     * them to the given $bookmarkId.
     *
     * @param int $bookmarkId the bookmark to associate the tags with
     * @param array $tagList the tags name
     */
    public function createTags($bookmarkId, $tagList)
    {
      if ($tagList == '') {
        return;
      }

      $tags = explode(',', $tagList);

      foreach ($tags as $tag) {
        $t = new Tag();
        $t->setBookmarkId($bookmarkId);
        $t->setName(trim($tag));
        $t->save();
      }
    }
}